# coding=utf-8
import os
from django.contrib import auth
from rest_framework.response import Response
from rest_framework.views import APIView

from backstage import forms
from backstage.utils import view_funcs


class Login(APIView):

    def post(self, request):
        """
        后台登录接口
        """
        form = forms.Login(request.data)
        if not form.is_valid():
            return Response({
                "status": 400,
                "msg": "parameter error",
            })

        # login_id = request.cookies.get("LOGIN_ID")
        # if not login_id:
        #     return Response({
        #         "status": 410,
        #         "msg": "gone",
        #     })

        # captcha_text = view_funcs.get_captcha_text(login_id)
        # if not captcha_text:
        #     return Response({
        #         "status": 410,
        #         "msg": "gone",
        #     })

        data = form.cleaned_data
        # if data["cap"] != captcha_text:
        #     return Response({
        #         "status": 403,
        #         "msg": "forbidden"
        #     })

        user = auth.authenticate(
            uid=data["uid"], password=data["password"])

        # 只允许管理员登录
        print(user)
        if not user or not user.is_admin:
            return Response({
                "status": 401,
                "msg": "unauthorized",
            })

        user.backend = "django.contrib.auth.backends.ModelBackend"
        auth.login(request, user)
        return Response({
            "status": 200,
            "msg": "success",
        })


class LoginCatpatcha(APIView):

    def get(self, request):
        """
        获取登录验证码
        """
        login_id, cap_data = view_funcs.generate_login_captcha()
        response = Response({
            "cap_data": cap_data,
        })
        response.set_cookie("LOGIN_ID", login_id)
        return response


class GitWebhookBackend(APIView):

    def post(self, request):
        os.chdir('/opt/sutras/')
        os.system('git pull')
        return Response({
            "status": 200,
            "msg": "success",
        })


class GitWebhookFe(APIView):

    def post(self, request):
        os.chdir('/opt/fujingxiangmu/')
        os.system('git pull')
        return Response({
            "status": 200,
            "msg": "success",
        })
